//
//  GroupViewController.m
//  iengage
//
//  Created by Luis Ziliani on 2/9/09.
//  Copyright Manas 2009. All rights reserved.
//

#import "GroupViewController.h"
#import "iengageAppDelegate.h"
#import "GroupParser.h"
#import "UserViewController.h"
#import "CurrentUserViewController.h"
#import "Util.h"

#define SecondsWaitedForLocation	5.0
#define MaxLengthUserNameDisplayed	17


@implementation GroupViewController

@synthesize navigationController;
@synthesize users;
@synthesize currentUser;
@synthesize fileName;
@synthesize location;


#pragma mark ProgressIndication

- (void) startProgressIndicator:(NSString*)msg {
	[activityIndicator startAnimating];
	activityCount++;
	[indicatorLabel setText:@"Working..."];
	[[self tableView] setTableHeaderView: activityIndicator];
	
	[refreshLocationButton setEnabled:NO];
}

- (void) stopProgressIndicator {
	if (activityCount > 0) {
		activityCount--;
	}
	
	if (activityCount == 0) {
		[[self tableView] setTableHeaderView:nil];
		[refreshLocationButton setEnabled:YES];
	}
}

#pragma mark Alerts

- (void) informErrorWithTitle: (NSString*) title error: (NSString*) msg dismissButton: (NSString*) buttonLabel {
	[self stopProgressIndicator];
	
	[UIAlertView showWithTitle:@"Error"	message:msg dismissButton: buttonLabel];
}	

- (void) informUnkownError {
	[self stopProgressIndicator];

	[self informErrorWithTitle:@"Error"
						 error:@"Unknown error. The application must be restarted."
				 dismissButton:nil];
}

- (void) informError: (NSString*) error {
	[self stopProgressIndicator];

	NSString * msg = [[NSString alloc] initWithFormat:@"There has been an error during the downloading of the information. Perhaps a bad configuration? The error is %@", error];
	[self informErrorWithTitle:@"Error"
						 error:msg
				 dismissButton: @"OK"];
	[msg release];

	[self tryContinueWithOldData];
}

- (void) informParseError {
	[self stopProgressIndicator];

	NSString * msg = [[NSString alloc] initWithFormat:@"The information downloaded is incorrect."];
	[self informErrorWithTitle:@"Error"
						 error:msg
				 dismissButton: @"OK"];
	[msg release];
}

- (void) showPreferencesCredentialsAreIncorrect {
	[self stopProgressIndicator];

	[self informErrorWithTitle:@"User or password incorrect"
						 error:@"The user and password provided are incorrect. Please go to \"Settings -> iengage\" and check them."  
				 dismissButton:@"OK"];
	[self tryContinueWithOldData];
}


#pragma mark Logic

- (void) tryContinueWithOldData {
	// try to locate old data
	if ([[NSFileManager defaultManager] fileExistsAtPath:[self fileName]]) {
		[self parseFile];
	}	
}


-(void) downloadUsers {
	[self startProgressIndicator:@"Downloading information..."];
	
	[self setUsers: nil];
	[self setUsers: [[UserCollection alloc] init]];
	
	FileDownload * download = [[[FileDownload alloc] init] autorelease];
	
	IEngageAppDelegate *app = [[UIApplication sharedApplication] delegate];
	
	[download startDownloadURL:[app groupServiceURL] 
					  withUser:[app currentUser] 
				   andPassword:[app userPassword] 
						  file:[self fileName] 
					  delegate:self];
}


- (void) requestEndedOk {
	[self stopProgressIndicator];
	[self parseFile];
}

- (void) locateAndExtractCurrentUser {
	id app = [[UIApplication sharedApplication] delegate];
	id curUser = [app currentUser];
	
	User *user = [users userByLogin: curUser];
	[self setCurrentUser: user];
	
	if (user != nil) {
		[users removeUser: user];
		[locateMeButton setEnabled:YES];
	}
}

- (void) updateUsersWithLocation {
	if (location != nil) {
		[self setUsers:[users sortByLocation:location]];
	
		// set current user coordinates
		[currentUser setLongitude:[location coordinate].longitude];
		[currentUser setLatitude:[location coordinate].latitude];
	}
}

- (void) parseFile {
	[self startProgressIndicator:@"Reading information..."];
	
	GroupParser * parser = [[GroupParser alloc] init];
	BOOL parsedOK = [parser parse: [self fileName]];
	
	if (!parsedOK) {
		[self informParseError];
	}
	else {
		[self setUsers:[parser users]];
		[self locateAndExtractCurrentUser]; // the current user must be eliminated from the users
		[self updateUsersWithLocation];
	}
	[parser release];
	[[self tableView] reloadData];
	[self stopProgressIndicator];
}

- (void) startLookingForLocation:(NSTimeInterval) seconds {
	[self startProgressIndicator:@"Looking for location..."];
	locationController = [[MyCLController alloc] initWithDelegate:self];
	[locationController refreshLocationWaiting:seconds];
}

- (void) refresh {
	[self startLookingForLocation: SecondsWaitedForLocation];
	[self downloadUsers];
}

- (void) locateMe {
	CurrentUserViewController* userViewController = [[CurrentUserViewController alloc] initWithNibName:@"CurrentUserView" 
																								bundle:nil 
																								  user:currentUser];
	
	userViewController.navigationController = navigationController;
	
	[navigationController pushViewController:userViewController animated:YES];
	
	[userViewController autorelease];	
}

- (void) restoreLocation {
	IEngageAppDelegate *app = [[UIApplication sharedApplication] delegate];
	double lat = [[app appState] lastUserLatitude];
	double lon = [[app appState] lastUserLongitude];
	
	if (lat != 0.0 || lon != 0.0) {
		[self setLocation: [[[CLLocation alloc] initWithLatitude:lat longitude:lon] autorelease]];
	}
}

- (void) showUser:(User *) user {
	UserViewController* userViewController = [[UserViewController alloc] initWithNibName:@"UserView" bundle:nil user:user];
	
	userViewController.navigationController = navigationController;
	
	[navigationController pushViewController:userViewController animated:YES];
	
	[userViewController release];
}

- (void) restoreLastViewedUser {
	IEngageAppDelegate *app = [[UIApplication sharedApplication] delegate];
	NSString * lastUser = [[app appState] lastUserViewed];
	
	if (![NSString isNullOrEmpty:lastUser]) {
		User *user = [users userByLogin:lastUser];
		if (user != nil) {
			[self showUser: user];
		}
	}
}

- (void) loadFileName {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
														 NSUserDomainMask, YES); 
	NSMutableString *documentsDirectory = [[NSMutableString alloc] initWithString: [paths objectAtIndex:0]]; 
	[documentsDirectory appendString:@"/groups.xml"];
	[self setFileName: documentsDirectory];
	[documentsDirectory release];
}


-(void) saveUserLocation {
	IEngageAppDelegate *app = [[UIApplication sharedApplication] delegate];
	[[app appState] setLastUserLatitude: [[self location] coordinate].latitude];
	[[app appState] setLastUserLongitude:[[self location] coordinate].longitude];
}


#pragma mark Location

-(void)locationUpdate:(CLLocation *)loc {
	[locationController release];
	
	[self setLocation: loc];
	
	[self updateUsersWithLocation];
	[[self tableView] reloadData];
	[self stopProgressIndicator];
	
	[self saveUserLocation];
}

-(void)locationError:(NSString *)text {
	[locationController release];
	[self informErrorWithTitle:@"Location problem" error:text dismissButton:@"OK"];
}

#pragma mark View methods

- (void)viewDidAppear:(BOOL)animated {
	IEngageAppDelegate *app = [[UIApplication sharedApplication] delegate];
	[[app appState] setLastUserViewed:nil];
}


- (void)viewDidLoad {
	[super viewDidLoad];

	[self restoreLocation];
	
	activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	CGRect rect;
	rect.origin.x = [activityIndicator bounds].size.width + 5;
	rect.size.width = [[self view] bounds].size.width;
	rect.size.height = 20;
	
	indicatorLabel = [[UILabel alloc] initWithFrame:rect];
	[indicatorLabel setText:@"Working..."];
	[indicatorLabel setFont: [[indicatorLabel font] fontWithSize:10]];
	[activityIndicator addSubview:indicatorLabel];
	
	refreshLocationButton = [[UIBarButtonItem alloc] initWithTitle:@"Refresh" 
																style:UIBarButtonSystemItemDone 
															   target:self
															   action:@selector(refresh)];
	
	locateMeButton = [[UIBarButtonItem alloc] initWithTitle:@"Me" 
															 style:UIBarButtonSystemItemDone 
															target:self
															action:@selector(locateMe)];
	[locateMeButton setEnabled:NO];
	
	[self setTitle:@"GeoChat"];
	[[self navigationItem] setRightBarButtonItem:refreshLocationButton];
	[[self navigationItem] setLeftBarButtonItem:locateMeButton];
	
	[self startLookingForLocation: SecondsWaitedForLocation];
	
	// try to locate old data
	if ([[NSFileManager defaultManager] fileExistsAtPath:[self fileName]]) {
		[self parseFile];
		
		[self restoreLastViewedUser];
		return;
	}
	else {
		[self downloadUsers];
	}
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self users] count];
}


- (NSString *) getDirecionString: (double) angle {
	if (angle >= 340.0 || angle <= 20.0) {
		return @"N";
	}
	else if (angle > 20.0 && angle < 70.0) {
		return @"NE";
	}
	else if (angle >= 70.0 && angle <= 110.0) {
		return @"E";
	}
	else if (angle > 110.0 && angle < 160.0) {
		return @"SE";
	}
	else if (angle >= 160.0 && angle <= 200.0) {
		return @"S";
	}
	else if (angle > 200.0 && angle < 250.0) {
		return @"SW";
	}
	else if (angle >= 250.0 && angle <= 290.0) {
		return @"W";
	}
	else {
		return @"NW";
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	User* user = [[self users] userAtIndex:[indexPath row]];
	
	CGRect frame = CGRectZero;
	
	UITableViewCell* cell = [[[UITableViewCell alloc] initWithFrame:frame reuseIdentifier:nil] autorelease];
	
	
	if ([[user displayName] length] > MaxLengthUserNameDisplayed){
		cell.text = [[[user displayName] substringToIndex:MaxLengthUserNameDisplayed] stringByAppendingString:@"..."];
	} else {
		cell.text = [user displayName];
	}
	
	UILabel* value = [[[UILabel alloc] initWithFrame:CGRectMake(220.0, 12.0, 200.0, 25.0)] autorelease];
	
	value.font = [UIFont systemFontOfSize:12.0];
	value.textColor = [UIColor blueColor];
	value.lineBreakMode = UILineBreakModeWordWrap;
	value.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	
	if ([user lastDistance] == UserDistanceNotCalculated){
		value.text = @"";
	} else {
		double distance = [user lastDistance];
		//Convert to km
		distance =  distance  / 1000;
		NSString *direction = [self getDirecionString:[user lastDirectionAngle]];
		value.text = [[[NSString alloc] initWithFormat:@"%.2f kms %@", distance, direction] autorelease];
	}	
	
	[cell.contentView addSubview:value];
	
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	User* user = [users userAtIndex:indexPath.row];
	
	[self showUser: user];
}


- (id) init {
	self = [super init];
	if (self != nil) {
		[self loadFileName];
	}
	return self;
}

- (void)dealloc {
	[self setUsers:nil];
	[locationController release];
	[location release];
	[refreshLocationButton release];
	[locateMeButton release];
	[indicatorLabel release];
	[activityIndicator release];
	[currentUser release];
    [super dealloc];
}

@end

